import { CrsClient } from "../../crsClient"
import { config } from "../../config"

const systemInfo = wx.getSystemInfoSync()

const SELECT_TYPE = {
  NONE: 0,
  IMAGE: 1,
  VIDEO: 2,
}
const App = getApp()
Page({
  data: {
    src: "",
    downImagePath: "",
    img: "",
    codePath: "",
    showOverlay: true,
    showSelect: false,
    SELECT_TYPE: SELECT_TYPE,
    selectType: 0,
    imgIndex: 1,
    imgList: [],
    on: true, // 控制音乐的状态，以及图标是否旋转
    musicList: [
      {
        title: "音乐1",
        src: config.api_blink_url + "/tree-music1.mp3",
        id: 0,
      },
      {
        src: config.api_blink_url + "/tree-music2.mp3",
        title: "音乐2",
        id: 1,
      },
      {
        src: config.api_blink_url + "/tree-music3.mp3",
        title: "音乐3",
        id: 2,
      },
    ],
    config: {
      minInterval: 1000, //最短的两次CRS请求间隔
    },
    windowWidth: 0,
    windowHeight: 0,
  },

  /** @type {CameraFrameListener} 相机帧回调 */
  listener: undefined,
  /** @type {HTMLCanvasElement} canvas对象 */
  canvas: undefined,

  /** @type {boolean} 是否需要持续识别，在点击“识别体验”之后和识别成功之前为true */
  runningCrs: undefined,
  /** @type {boolean} 当前是否正在进行CRS请求 */
  busy: undefined,
  /** @type {CrsClient} 负责发起CRS请求的对象 */
  crsClient: undefined,
  /** @type {number} 最后一次CRS请求的事件，用于判断是否满足最短请求间隔 */
  last: undefined,
  num: 0,

  onLoad: function () {},
  onReady: function () {
    // 获取BackgroundAudioManager 实例
    // this.back = wx.getBackgroundAudioManager()
    // // 对实例进行设置
    // this.back.src = config.api_blink_url + "/tree-music1.mp3"
    // this.back.title = "风的声音" // 标题为必选项
    // this.back.play() // 开始播放
    // this.back.onEnded((res) => {
    //   this.back.src = config.api_blink_url + "/tree-music1.mp3"
    //   this.back.title = "风的声音" // 标题为必选项
    //   this.back.play()
    // })
    this.ctx = wx.createCameraContext()
    this.selectComponent("#music-cmp").initMusic(0)
    this.getInfo()
    this.downImage()
    this.saveSignRecord()
  },
  //页面跳转
  onJumpMin() {
    wx.navigateToMiniProgram({
     appId: 'wxe9bc7c69463b5455', // 需要跳转到指定的小程序appid
     path: '',   // 打开的页面
     envVersion: 'release',
     success(res) {
      // 打开成功
      console.log(res);
     }
    })
   },
   saveSignRecord(){//打卡成功
    wx.request({
      url: `https://www.pdjlixiang.com/cip-rest/thirdParty/saveSignRecord`,
      method: "post",
      data:{
        openid:App.globalData.uid,
        code:'ARLHY'
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', //修改此处即可
        'token':App.globalData.token
      },
      success: (res) => {
        console.log(res)
        this.tip()
      }
    })
   },
   //打卡成功提示
   tip(){
    wx.showToast({
      title: '打卡成功',
      icon: 'loading',
      duration: 2000
    })
    setTimeout(function(){
      wx.hideToast()
    },3000)
   },
  showLoading(text) {
    this.setData({
      showLoading: true,
      showLoadingText: text,
    })
  },
  hideLoading() {
    this.setData({
      showLoading: false,
    })
  },
  getInfo: function () {
    var _this = this
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  //图像识别部分：

  onShow: function () {
    if (this.listener) this.listener.start() //页面隐藏时相机帧的监听会自动停止，但恢复展示时不会自动启动，这里手动启动
  },

  onCameraInit: function () {
    //找到canvas对象
    const query = wx.createSelectorQuery()
    query
      .select("#capture")
      .fields({
        node: true,
      })
      .exec((res) => {
        const canvas = res[0].node
        //设置canvas内部尺寸为480*640，frame-size="medium"的设置下相机帧大多是480*640
        canvas.width = this.data.windowWidth
        canvas.height = this.data.windowHeight
        this.canvas = canvas

        this.crsClient = new CrsClient(this.data.config, this.canvas)

        //开始监听相机帧
        let cameraContext = wx.createCameraContext()
        this.listener = cameraContext.onCameraFrame((frame) => {
          if (!this.canvas) return
          let canvas = this.canvas
          //如果尺寸不匹配，就修改canvas尺寸以适应相机帧
          if (canvas.width !== frame.width || canvas.height !== frame.height) {
            canvas.width = frame.width
            canvas.height = frame.height
          }
          //  console.log(frame)
          this.queryImage(frame)
        })
        this.listener.start()
      })
  },
  queryImage: function (frame) {
    if (this.busy) return
    //最短的两次CRS请求间隔
    let now = new Date().getTime()
    if (this.last && now - this.last < this.data.config.minInterval) return
    this.last = now

    let base64 = this.crsClient.queryImage(frame)

    //如果正在进行CRS请求，就不允许再次请求
    //this.busy = true
    setTimeout(() => {
      this.busy = true
      var aa = wx.getFileSystemManager()
      aa.writeFile({
        filePath: wx.env.USER_DATA_PATH + "/test.png",
        data: base64,
        encoding: "base64",
        success: (res) => {
          wx.saveImageToPhotosAlbum({
            filePath: wx.env.USER_DATA_PATH + "/test.png",
            success: function (res) {
              wx.showToast({
                title: "保存成功",
              })
            },
            fail: function (err) {
              console.log(err)
            },
          })
          console.log(res)
        },
        fail: (err) => {
          console.log(err)
        },
      })
    }, 1000)
    // if(this.busy){
    //   console.log(base64)
    //   var aa = wx.getFileSystemManager();
    //     aa.writeFile({
    //       filePath: wx.env.USER_DATA_PATH + '/test.png',
    //       data: base64,
    //       encoding: 'base64',
    //       success: res => {
    //         wx.saveImageToPhotosAlbum({
    //           filePath: wx.env.USER_DATA_PATH + '/test.png',
    //           success: function (res) {
    //             wx.showToast({
    //               title: '保存成功',
    //             })
    //           },
    //           fail: function (err) {
    //             console.log(err)
    //           }
    //         })
    //         console.log(res)
    //       },
    //       fail: err => {
    //         console.log(err)
    //       }
    //     })
    // }
  },
  //截图
  downImage() {
    var that = this
    wx.downloadFile({
      // url: "https://www.pdjlixiang.com:8801/assets/bg.png",
      url: "https://www.pdjlixiang.com:8801/assets//LH-Share.png",
      success(res) {
        console.log(res)
        that.setData({
          downImagePath: res.tempFilePath,
        })
      },
    })
    wx.downloadFile({
      url: "https://www.pdjlixiang.com:8801/assets/ScanCode.jpg",
      success(res) {
        that.setData({
          codePath: res.tempFilePath,
        })
      },
    })
  },
  takePhoto() {
    var that = this
    wx.showLoading({
      title: "截图中..",
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 6000)
    that.ctx.takePhoto({
      quality: "high",
      success: (res) => {
        console.log(res)
        var temp = res.tempImagePath
        this.setData({
          src: temp,
        })
        console.log(temp)
        //相当于h5的获取ID值
        const cts = wx.createCanvasContext("photos")
        // console.log(cts)
        cts.drawImage(temp, 0, 0, this.data.windowWidth, this.data.windowHeight)
        cts.drawImage(
          this.data.downImagePath,
          0,
          0,
          this.data.windowWidth,
          this.data.windowHeight
        )
        cts.drawImage(this.data.codePath, 5, 5, 50, 50)
        cts.draw(false, () => {
          that.draw()
        })
      },
    })
  },
  draw() {
    wx.canvasGetImageData({
      canvasId: "photos",
      x: 0,
      y: 0,
      width: this.data.windowWidth,
      height: this.data.windowHeight,
      success(res) {
        console.log(res)
        //比较重要的代码
        const upng = require("../../UPNG")
        let png = upng.encode([res.data.buffer], res.width, res.height)
        let base64 = wx.arrayBufferToBase64(png)
        console.log(base64)
        var aa = wx.getFileSystemManager()

        aa.writeFile({
          filePath: wx.env.USER_DATA_PATH + "/test.png",
          data: base64,
          encoding: "base64",
          success: (res) => {
            wx.saveImageToPhotosAlbum({
              filePath: wx.env.USER_DATA_PATH + "/test.png",
              success: function (res) {
                wx.showToast({
                  title: "保存成功",
                })
              },
              fail: function (err) {
                console.log(err)
              },
            })
            console.log(res)
          },
          fail: (err) => {
            console.log(err)
          },
        })
      },
    })
  },
  //音乐控制
  musicControl: function () {
    this.setData({
      on: !this.data.on,
    })
    // if (this.data.on) {
    //   this.back.play()
    // } else {
    //   this.back.pause()
    // }
    this.selectComponent("#music-cmp").soundControl(this.data.on)
  },
  //分享按钮
  shareClick() {
    //this.onCameraInit()
  },
  onShareAppMessage: function () {
    return {
      title: "微信AR", // 转发标题
      path: "pages/content/index", // 自定义页面路径中携带的参数，可带参数 如 path?a=1&b=2 的 “?” 后面部分
      imageUrl: "", //使用默认截图, 自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4
    }
  },
  onResult: function (target) {},
})
